package com.example.bookmanage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookmanage.domain.user.dto.SysUserDTO;
import com.example.bookmanage.domain.user.dto.SysUserEditDTO;
import com.example.bookmanage.domain.user.dto.SysUserQueDTO;
import com.example.bookmanage.domain.user.SysUser;
import com.example.bookmanage.domain.user.dto.SysUserUpStatusDTO;
import com.example.bookmanage.domain.user.vo.SysUserVO;
import com.example.bookmanage.enums.UserEntity;
import com.example.bookmanage.exception.ServiceException;
import com.example.bookmanage.enums.ResultCode;
import com.example.bookmanage.service.SysUserService;
import com.example.bookmanage.mapper.SysUserMapper;
import com.example.bookmanage.utils.BCryptUtils;
import com.example.bookmanage.utils.ThreadLocalUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    public String login(String username, String password) {

        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username));
        if (sysUser == null) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        if (!BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            throw new ServiceException(ResultCode.ACCOUNT_PASSWORD_ERROR);
        }

        return tokenService.createToken(sysUser.getUserId(), secret, UserEntity.ADMIN.getValue(), sysUser.getNickname());
    }

    /**
     * 用户列表
     *
     * @param sysUserQueDTO
     * @return
     */
    public List<SysUserVO> list(SysUserQueDTO sysUserQueDTO) {
        PageHelper.startPage(sysUserQueDTO.getPageNum(), sysUserQueDTO.getPageSize());
        return sysUserMapper.selectUserList(sysUserQueDTO);
    }

    /**
     * 添加用户
     *
     * @param sysUserDTO
     * @return
     */
    public boolean add(SysUserDTO sysUserDTO) {
        // 检查用户名是否已存在
        String username = sysUserDTO.getUsername();
        if (exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username))) {
            throw new ServiceException(ResultCode.USER_EXIST);
        }

        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(sysUserDTO, sysUser);

        sysUser.setPassword(BCryptUtils.encryptPassword(sysUser.getPassword()));
        sysUser.setStatus(0);

        return save(sysUser);
    }

    /**
     * 更新用户
     *
     * @param sysUserEditDTO
     * @return
     */
    public boolean update(SysUserEditDTO sysUserEditDTO) {

        boolean exists = exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, sysUserEditDTO.getUserId()));
        if (!exists) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }

        SysUser sysUser = new SysUser();
        BeanUtil.copyProperties(sysUserEditDTO, sysUser);
        return updateById(sysUser);

    }

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    public boolean deleteById(Long userId) {
        // 检查用户是否存在
        if (!exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, userId))) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        return removeById(userId);
    }

    /**
     * 更新用户状态
     *
     * @param sysUserUpStatusDTO
     * @return
     */
    public int updateUserStatus(SysUserUpStatusDTO sysUserUpStatusDTO) {
        if (!exists(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserId, sysUserUpStatusDTO.getUserId()))) {
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }

        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", sysUserUpStatusDTO.getUserId())
                .set("status", sysUserUpStatusDTO.getStatus());
        return sysUserMapper.update(null, updateWrapper);
    }

    /**
     * 更新用户头像
     *
     * @param sysUser
     */
    public void updateByImg(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    public SysUserVO getUserInfo() {
        Long userId = ThreadLocalUtil.get("userId", Long.class);
        SysUser sysUser = sysUserMapper.selectById(userId);

        SysUserVO sysUserVO = new SysUserVO();
        BeanUtil.copyProperties(sysUser, sysUserVO);
        return sysUserVO;
    }

}
